package com.zee.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zee.admin.dao.SysParamsDao;
import com.zee.admin.entity.SysParams;
import com.zee.admin.model.dto.SysParamsDTO;
import com.zee.admin.model.dto.SysParamsQueryDTO;
import com.zee.admin.model.excel.SysParamsExcel;
import com.zee.admin.model.response.AdminCode;
import com.zee.admin.service.ISysParamsService;
import com.zee.common.exception.ExceptionCast;
import com.zee.common.utils.ConvertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysParamsServiceImpl extends ServiceImpl<SysParamsDao, SysParams> implements ISysParamsService {

    @Override
    public Page<SysParams> page(SysParamsQueryDTO dto) {
        Map<String, Object> params = BeanUtil.beanToMap(dto);
        return baseMapper.selectPage(new Page<>(dto.getPage(), dto.getPageSize()), this.getWrapper(params));
    }

    @Override
    public List<SysParamsExcel> exportList(HashMap<String, Object> params) {
        List<SysParams> sysParams = baseMapper.selectList(getWrapper(params));
        return ConvertUtil.sourceToTarget(sysParams, SysParamsExcel.class);
    }

    private LambdaQueryWrapper<SysParams> getWrapper(Map<String, Object> params) {
        String paramCode = (String) params.get("paramCode");

        LambdaQueryWrapper<SysParams> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysParams::getParamType, 1);
        wrapper.like(StringUtils.isNotBlank(paramCode), SysParams::getParamCode, paramCode);

        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysParamsDTO dto) {
        //参数编码查重
        String valueByCode = baseMapper.getValueByCode(dto.getParamCode());
        if (valueByCode != null) {
            ExceptionCast.cast(AdminCode.PARAMS_CODE_IS_EXIST);
        }
        SysParams sysParams = ConvertUtil.sourceToTarget(dto, SysParams.class);
        //只能增加非系统参数，此处可省略，因为不写数据库默认是1，只是为了代码阅读方便
        sysParams.setParamType(1);
        this.save(sysParams);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysParamsDTO dto) {
        //参数编码查重
        SysParams paramsByCode = baseMapper.getParamsByCode(dto.getParamCode());
        if (paramsByCode != null && !dto.getId().equals(paramsByCode.getId())) {
            ExceptionCast.cast(AdminCode.PARAMS_CODE_IS_EXIST);
        }

        SysParams sysParams = ConvertUtil.sourceToTarget(dto, SysParams.class);
        this.updateById(sysParams);
    }

}